<?
    /**
     * Smarty plugin
     * @package Smarty
     * @subpackage plugins
     * @author Kulikov Alexey <a.kulikov@gmail.com>
     */


    /**
     *
     */
    function smarty_function_load_rating($params, &$smarty){
        global $db, $nodeData; // create a link to the database connection

        //pre-process parameters
        //variable name
        if(empty($params['var'])){
            $var = 'rating';
        }else{
            $var = $params['var'];
        }


        //only pages can be rated, not folders!
        if(empty($nodeData['pageref'])){            
            return;
        }
                
        //load the rating data
        $type             = $db->getOne("SELECT id FROM datatype WHERE codeset = ".$db->qstr($nodeData['codeset']));
        $rating           = $db->getRow("SELECT rating, votes FROM page_ratings WHERE pageid = ".(int)$nodeData['objectid']." AND pagetype = ".(int)$type);
        $rating['pid']    = (int)$nodeData['objectid'];
        $rating['ptype']  = (int)$type;
        
        if($rating['votes'] > 0){
            $rating['rating'] = round($rating['rating']/$rating['votes']);
        }else{
            $rating['rating'] = 0;
        }
                
        //see if I have rating this page
        $rating['rated']  = $db->getOne("SELECT ip FROM page_ratings_history_anon WHERE pageid = ".$rating['pid']." AND pagetype = ".$rating['ptype']." AND ip = ".ip2long($_SERVER['REMOTE_ADDR']));
        
        //give all this shit to smarty
        $smarty->assign($var,$rating);
    }
?>